//
//  AfanOauthViewController.swift
//  weibo
//
//  Created by afan on 16/3/25.
//  Copyright © 2016年 阿范. All rights reserved.
//

import UIKit
import SVProgressHUD

class AfanOauthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "新浪微博"
        view = webView
        webView.delegate = self
        setupNavigationBar()
        
        //提示
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.None)
        
        //拼接 URL    // 登陆界面的url需要查看api文档
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        ///加载请求
        webView.loadRequest(request)
        
    }
    
    /// 设置导航栏
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //MARK: 点击事件
    ///关闭窗口
    @objc private func close() {

        dismissViewControllerAnimated(true, completion: nil)
    }
    ///填充按钮
    @objc private func autoFill() {
        let jsCode = "document.getElementById('userId').value='13192330009';document.getElementById('passwd').value='fanzhenghao..'"
        
        // 执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    
    
    // MARK: - 懒加载
    /// webView
    private lazy var webView: UIWebView = UIWebView()

}

extension AfanOauthViewController: UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
    //webView 是否加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        ///绝对 URL
        let urlString = request.URL!.absoluteString
        
        //判断头部是否有回调地址 没有就继续加载
        if !urlString.hasPrefix(redirect_uri){
            return true
        }else{
            //加载的是回调地址
            //在判断回调地址后面的参数
            //获得 get 请求后面的参数
            let query = request.URL?.query
            //判断是否以"code="开头
            let codeString = "code="
            if query!.hasPrefix(codeString){
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
//                print("code:\(code)")
                
                //调用自定义办法加载 access_Token
//               AfanUserAccountViewModel.sharedInstance.loadAccessToken(code)
                AfanUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil{
                        SVProgressHUD.showErrorWithStatus("获取用户数据失败")
                        // 延迟1秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        
                        return
                    }
                    AppDelegate.outSwithRootViewController(AfanMainViewontroller())
                    self.close()
                })
                
            }else{
                close()
            }
        }
        return false
    }
    
    
    
}

































